<?php
/**
 * Created by PhpStorm.
 * User: blue
 * Date: 2018/8/1
 * Time: 20:16
 */

namespace app\api\service;


use app\lib\exception\ParamException;

/**
 * Class AccessToken
 * @package  微信accessToken管理
 */
class AccessToken
{
    private $url;
    const TOKEN_CACHED_KEY="access";
    const TOKEN_EXPIRE_IN=7000;

    public function __construct()
    {
        $appid=config('wx.app_id');
        $secret=config('wx.app_secret');
        $url=config("wx.accessToken");
        $this->url=sprintf($url,$appid,$secret);
    }

    /**
     * 获取accessToken
     */
     public static function getAccessToken(){
        // 先判断缓存中存在不存在accessToken，存在取出返回。不存在请求接口返回。
        $accessToken=cache('accessToken');
        if($accessToken){
            return $accessToken;
        }else{
            $token=curl_request(self::$url);
            $tokenArr=json_decode($token,true);
            if($token){
                throw new ParamException(['msg'=>accessToken令牌为空]);
            }
            if(array_key_exists(errcode,$tokenArr)){
                throw new ParamException(['msg'=>$tokenArr['errmsg']]);
            }
            //写入缓存
            cache('accessToken',self::TOKEN_CACHED_KEY,self::TOKEN_EXPIRE_IN);
            return $token;
        }
    }
}